package jmu.edu.yjc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jmu.edu.yjc.constants.SystemConstants;
import jmu.edu.yjc.server.WebSocketServer;
import jmu.edu.yjc.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.nio.charset.StandardCharsets;

/**
 * 消息监听对象，接收订阅消息
 */
@Component
public class RedisReceiver implements MessageListener {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private MessageService messageService;
    /**
     * 处理接收到的订阅消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern)
    {
        String channel = new String(message.getChannel());// 订阅的频道名称
        String msg = "";
        log.info("监听到消息");
        try
        {
            msg = new String(message.getBody(), StandardCharsets.UTF_8);//注意与发布消息编码一致，否则会乱码
            if (!StringUtils.isEmpty(msg)){
                if (channel.endsWith(SystemConstants.REDIS_CHANNEL_MAIL)){
                    // websocket连接关闭的消息
                    JSONObject json = JSON.parseObject(msg);
                    // 获取用户ID
                    Long userId = json.getLong("receiverUserId");
                    if(WebSocketServer.webSocketMap.containsKey(userId)) {
                        log.info("用户Id" + userId + "收到邮件消息");
                        Session session = WebSocketServer.webSocketMap.get(userId);
                        session.getAsyncRemote().sendText(msg);
                    }

                }else if (channel.endsWith(SystemConstants.REDIS_CHANNEL_SEND)){
                    // 向客户端推向消息的接口
                    JSONObject json = JSONObject.parseObject(msg);
                    if (json.getString("flag") != null){
                        if ("send".equals(json.getString("flag"))){
                            Long toUserId = json.getLong("toUserId");
                            if(WebSocketServer.webSocketMap.containsKey(toUserId)){
                                log.info("用户Id"+toUserId+"收到来自"+json.getString("userId")+"的消息");
                                Session session = WebSocketServer.webSocketMap.get(toUserId);
                                session.getAsyncRemote().sendText(json.getString("message"));
                            }
                        }
                    }else {
                        log.info("其它消息，不予处理");
                    }
                }
            }else{
                log.info("消息内容为空，不处理。");
            }
        }
        catch (Exception e)
        {
            log.error("处理消息异常："+e.toString());
            e.printStackTrace();
        }
    }
}
